package lmycc.test.demo.controller;

import lmycc.test.demo.domain.Encrypt;
import lmycc.test.demo.domain.Login_log;
import lmycc.test.demo.domain.Student;
import lmycc.test.demo.service.LogService;
import lmycc.test.demo.service.LoginService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.util.StringUtils.isEmpty;

@Controller
@Component
@Transactional
public class LoginController {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(currentTime);
    Encrypt encrypt = new Encrypt();
    HttpSession session;
    @Autowired
    private LoginService loginService;
    @Autowired
    private LogService logService;

    /**
     * 显示登录页面
     */
    @RequestMapping("/login")
    public String index() {
        return "/login";
    }

    /**
     * 登录
     */
    @RequestMapping(value = "/index")
    public String stuList(@Valid Student student, BindingResult bindingResult, HttpSession session, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            if (isEmpty(student.getName())) {
                request.setAttribute("name", "请输入账号");
                return "/login";
            } else if (isEmpty(student.getPassword())) {
                request.setAttribute("pwd", "请输入密码");
                return "/login";
            }
            return "/login";
        } else {
            student.setPassword(encrypt.SHA256(student.getPassword()));
            Student stu = loginService.login(student);
            if (!isEmpty(stu)) {
                Login_log login_Log = new Login_log();
                login_Log.setUser_id(stu.getId());
                login_Log.setActive("login");
                login_Log.setActive_date(dateString);
                logService.login_Log(login_Log);
                session.setAttribute("session", stu.getName());
                return "/index";
            } else {
                request.setAttribute("message", "账号或密码错误");
                return "/login";
            }
        }
    }

    /**
     * 添加user
     */
    @ResponseBody
    @RequestMapping("/insertUser")
    public Map addStu(@RequestBody String string) {
        Map message = new HashMap();
        Student student = new Student();
        JSONObject userJson = JSONObject.fromObject(string);
        student.setName(userJson.getString("name"));
        student.setDescription(userJson.getString("description"));
        student.setCreateDate(dateString);
        List<Student> list = loginService.findByName(student.getName());
        student.setPassword(encrypt.SHA256("123456+"));
        if (list.size() > 0) {
            message.put("message", "创建失败，账号已存在！");
            return message;
        } else {
            loginService.insertOne(student);
            message.put("message", "创建成功！");
            return message;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getUserList")
    public List<Student> getStuList() {
        login();
        List<Student> stuList = loginService.selectAll();
        return stuList;
    }

    /**
     * 重置密码
     */
    @RequestMapping("/reset")
    public String updateStu(@Valid Student student, BindingResult bindingResult, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            return "/login";
        }
        List<Student> list = loginService.findByName(student.getName());
        if (list.size() <= 0) {
            request.setAttribute("error", "用户不存在！！！");
            return "/login";
        } else {
            student.setPassword(encrypt.SHA256("123456+"));
            loginService.resetPwd(student);
            request.setAttribute("success", "已重置");
            return "/login";
        }
    }

    public void login() {
        try {
            if (isEmpty(session)) {
                index();
            }
        } catch (NullPointerException e) {
            index();
        }
    }
}
